﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using ExaminationSys.DataAccess.Repository;
using ExaminationSys.DataAccess;
using ExaminationSys.Helper;
using ExaminationSys.DataAccess.Entity;

namespace ExaminationSys.ashx
{
    /// <summary>
    /// AjaxLoginHandler 的摘要说明
    /// </summary>
    public class AjaxLoginHandler : IHttpHandler, IRequiresSessionState
    {

        private static readonly StudentService Proxy = ObjectFactory<StudentService>.Create();
        private static readonly LoginLogService LoginProxy = ObjectFactory<LoginLogService>.Create();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //uid=fe&pwd=d&code=d
            var uid = context.Request["uid"];
            var pwd = context.Request["pwd"];
            var vcode = context.Request["code"];
            var chkTmp = context.Request["chk"];

            var chk = false;
            bool.TryParse(chkTmp, out chk);

            var serverCode = context.Session["code"] as string;

            var hashpwd = DESHelper.Encrypt(pwd);
            var loginInfo = Proxy.Login(uid, hashpwd);
            if (!vcode.Equals(serverCode, StringComparison.OrdinalIgnoreCase))
            {
                context.Response.Write("201");
            }
            else if (loginInfo==null)
            {
                context.Response.Write("202");
            }
            else
            {
                context.Session["StudentInfo"] = loginInfo;
                if(chk)
                {
                    HttpCookie cookie = context.Request.Cookies["SJEDU_UID"];
                    if (cookie == null)
                    {
                        cookie = new HttpCookie("SJEDU_UID");
                    }

                    cookie.Values.Set("UID", uid);
                    cookie.Values.Set("PWD", hashpwd);
                    cookie.Expires = DateTime.Today.AddDays(7);
                    context.Response.SetCookie(cookie);
                }
                else
                {
                    HttpCookie cookie = context.Request.Cookies["SJEDU_UID"] ?? new HttpCookie("SJEDU_UID");

                    cookie.Values.Set("UID", uid);
                    cookie.Values.Set("PWD", hashpwd);
                    cookie.Expires = DateTime.Today.AddDays(1);
                    context.Response.SetCookie(cookie);
                }
                var entity = new LoginLog() { ID = Guid.NewGuid(), UserID = uid, LoginTime = DateTime.Now, LoginType = (int)LoginType.登录};
                LoginProxy.Insert(entity);
                context.Response.Write("200");
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}